const mongoose = require('mongoose');
const User = require('../model/user.model');

//增
exports.create = function(req,res,next){
    const user = new User(req.body);
    user.save().then(data => {
        res.json(data)
    });
}

//删
exports.remove = function(req,res,next){
    const id = req.params.id;
    User.findByIdAndRemove(id,function(err,data){
        res.json({message:'删除成功'});
    });
}

//改
exports.update = function(req,res,next){
    const id = req.params.id;
    User.findByIdAndUpdate(id,{$set:req.body},{new:false}).then(data => {
        res.json(data);
    });
}

//查
exports.list = function(req,res,next){
    var page = req.body.page ? req.body.page : 1;
    var rows = req.body.rows ? req.body.rows : 5;
    var queryCondition = {};


    if(req.body.name && req.body.name.trim().length>0){
        name = req.body.name;
        queryCondition = {
            name:new RegExp(name,'i')
        };
    }
    User.paginate(queryCondition,{page:page,limit:+rows},function(err,result){
        result.rows = result.docs;
        delete result.docs;
        res.json(result);
    })
}


exports.chaxun = function(req,res,next){
    var name = req.body.name;
    var password = req.body.password;
    User.find({name:name,password:password},function(err,result){
        if(result.length){
            res.json(result[0].name);
        }else{
            res.json(false);
        }
        
    })
}